package com.CST.service.impl;


import com.CST.common.api.Response;
import com.CST.common.api.ResultObject;
import com.CST.common.constant.Constants;
import com.CST.common.enumPackge.EnumIsUse;
import com.CST.common.method.CommonMethod;
import com.CST.entity.BdEnumFuzzy;
import com.CST.entity.BdEnumdetail;
import com.CST.mapper.dataplatform.BdDepartmentMapper;
import com.CST.mapper.dataplatform.BdEnumdetailMapper;
import com.CST.service.IBdEnumdetailService;
import com.CST.util.ExcelTransfer;
import com.CST.util.HttpUtil;
import com.CST.util.PageHelperTool;
import com.CST.vo.BdEnumDetailUnLinkVO;
import com.CST.vo.DeptHisRelationVO;
import com.CST.vo.DeptSalaryRelationVO;
import com.CST.vo.DeptUFIDARelationVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ly
 * @since 2021-09-23
 */
@Service
public class BdEnumdetailServiceImpl extends ServiceImpl<BdEnumdetailMapper, BdEnumdetail> implements IBdEnumdetailService {


    CommonMethod method = new CommonMethod();
    @Autowired
    private ExcelTransfer excelTransfer;

    @Override
    public List<BdEnumdetail> getEnumDetailSource(BdEnumdetail entity) {
        return baseMapper.getEnumDetailSource(entity);
    }

    @Override
    public List<BdEnumdetail> getLikeEnumDetailSource(BdEnumdetail entity) {
        return baseMapper.getLikeEnumDetailSource(entity);
    }

    @Override
    public Response addEnumDetail(BdEnumdetail entity) {
        if (entity.getEdParentCode().isEmpty() || entity.getEdName().isEmpty()) {
            return Response.error("枚举字段/名称不能为空");
        }

//        List<String> edExtraSecondDescriptions= new ArrayList<>();
//        String edExtraSecondCode = entity.getEdExtraSecondCode();
//        String[] deptCodes = edExtraSecondCode.split("-");
//        for (String deptCode : deptCodes) {
//            String deptName = bdEnumdetailMapper.selectDepartment(deptCode);
//            edExtraSecondDescriptions.add(deptName);
//        }
//        entity.setEdExtraSecondDescription(edExtraSecondDescription);

        try {
            if (entity.getEdCode() == null || entity.getEdCode().isEmpty()) {
                String maxValue = method.maxEdCode(baseMapper, entity.getEdParentCode());

                if (maxValue.isEmpty()) {
                    maxValue = "1";
                }
                entity.setEdCode(maxValue);
            } else {
 
                BdEnumdetail searchInfo = new BdEnumdetail();
                searchInfo.setEdCode(entity.getEdCode());
                searchInfo.setEdParentCode(entity.getEdParentCode());
                List<BdEnumdetail> searchDBRecord = baseMapper.getEnumDetailSource(searchInfo);
                if (CollectionUtils.isNotEmpty(searchDBRecord)) {
                    return Response.error("编号已存在!");
                }

            }

            setEntityValue(entity);
            baseMapper.addEnumDetail(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "添加失败:", ex.getMessage()));
        }
        return Response.success("添加成功");
    }

    @Override
    public Response modifyEnumDetail(BdEnumdetail entity) {
        if (entity.getEdId() == 0) {
            return Response.error("主键不能为空");
        }

        try {
//            BdEnumdetail entityValue = setEntityValue(entity);
            setEntityValue(entity);
//            baseMapper.modifyEnumDetail(entityValue);
            baseMapper.modifyEnumDetail(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "修改失败", ex.getMessage()));
        }
        return Response.success("修改成功");
    }


    /**
     * 将所有的规则全变成0后,再将设置默认的规则设置成1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(BdEnumdetail entity) {
        UpdateWrapper<BdEnumdetail> uw = new UpdateWrapper<>();
        uw.eq("edParentCode", entity.getEdParentCode());
        uw.set("edExtraFirstCode", "0");
        update(uw);
        setEntityValue(entity);
        baseMapper.modifyEnumDetail(entity);
//        System.setProperty("ruleCode", entity.getEdCode());
    }

    @Override
    public BdEnumdetail getDefaultCode(BdEnumdetail entity) {
        LambdaQueryWrapper<BdEnumdetail> lw = new LambdaQueryWrapper<>();
        lw.eq(BdEnumdetail::getEdExtraFirstCode, "1");
        lw.eq(BdEnumdetail::getEdEdId, entity.getEdEdId());
        List<BdEnumdetail> result = list(lw);
        if (CollectionUtils.isEmpty(result)) {
            return new BdEnumdetail();
        }
        return result.get(0);
    }

    @Override
    public Response batchDeleteEnumDetail(List<Integer> ids) {
        int size = ids.size();
        try {
            if (size==1)
            baseMapper.batchDeleteEnumDetail(ids);
        } catch (Exception ex) {
            return Response.error("删除失败");
        }
        return Response.success("删除成功");

    }

    /**
     * 根据查询标志判断查询的数据是已经关联的还是未关联的
     *
     * @param entity
     * @return
     */
    @Override
    public ResultObject listEnumDetailIsLink(BdEnumFuzzy entity) {
        // 查询到的全部映射结果
        List<BdEnumdetail> enumRelationInfos = baseMapper.listEnumDetailIsLink(entity);
        PageInfo<BdEnumdetail> bdEnumdetailPageInfo = PageHelperTool.excutePageInfo(enumRelationInfos,
                entity.getPageIndex(), entity.getPageSize());
        return ResultObject.successReturn(bdEnumdetailPageInfo);
//        return ResultObject.successReturn(enumRelationInfos);
    }

    /**
     * 根据entity的sysId和edParentCode查询未关联的 科室对应 数据
     *
     * @param entity
     * @return
     */
    @Override
    public ResultObject listEnumDetailUnLink(BdEnumFuzzy entity) {
        // 查询出所有未关联的数据
        List<BdEnumdetail> bdEnumdetailList = baseMapper.listEnumDetailUnLink(entity);
        // 存放所有已关联的数据 进行一个映射
        List<BdEnumDetailUnLinkVO> bdEnumDetailUnLinkVOList = new ArrayList<>();
        for (BdEnumdetail bdEnumdetail : bdEnumdetailList) {
            bdEnumDetailUnLinkVOList.add(new BdEnumDetailUnLinkVO(bdEnumdetail.getEdExtraFirstCode(),
                    bdEnumdetail.getEdExtraFirstDescription()));
        }

        if ("HIS".equals(entity.getSysId())){
            addEnumDetailUnLink(bdEnumDetailUnLinkVOList);
        }

        return ResultObject.successReturn(bdEnumDetailUnLinkVOList);
    }
    public void addEnumDetailUnLink(List<BdEnumDetailUnLinkVO> list) {
        list.addAll(baseMapper.selectBdEnumDetailUnLink(LocalDate.now().getYear()));
    }

    @Override
    public ResultObject listEnumDetail(BdEnumdetail bdEnumdetail) {
        List<BdEnumdetail> enumDetailSource = baseMapper.getEnumDetailSource(bdEnumdetail);
        return ResultObject.successReturn(enumDetailSource);
    }

    /**
     * 获取对应关系的edFirst字段
     * 根据edParentCode确定
     *
     * @param bdEnumdetail
     * @return
     */
    @Override
    public List<BdEnumdetail> listEdFirstByFuzzy(BdEnumdetail bdEnumdetail) {
        List<BdEnumdetail> bdEnumdetailList = baseMapper.listEdFirstByFuzzy(bdEnumdetail);
        return bdEnumdetailList;
    }

    @Override
    public void exportExcelDeptSalaryRelation(HttpServletResponse response) throws ClassNotFoundException {
        BdEnumFuzzy enumFuzzy = new BdEnumFuzzy();
        enumFuzzy.setEdEdId(1).setEdId(0).setEdOrder(0).setEdParentCode("RD_DeptSalaryRelation").setSysId("Salary");
        List<DeptSalaryRelationVO> list = new GetVos<DeptSalaryRelationVO>().getVos(enumFuzzy,
                DeptSalaryRelationVO.class);
        excelTransfer.exportExcel(response, list, "工资对应", "sheet", DeptSalaryRelationVO.class);
    }

    @Override
    public void exportExcelDeptHisRelation(HttpServletResponse response) throws ClassNotFoundException {
        BdEnumFuzzy enumFuzzy = new BdEnumFuzzy();
        enumFuzzy.setEdEdId(1).setEdId(0).setEdOrder(0).setEdParentCode("RD_DeptHisRelation").setSysId("HIS");
        List<DeptHisRelationVO> list = new GetVos<DeptHisRelationVO>().getVos(enumFuzzy, DeptHisRelationVO.class);
        excelTransfer.exportExcel(response, list, "HIS科室", "sheet", DeptHisRelationVO.class);
    }

    @Override
    public void exportExcelDeptUFIDARelation(HttpServletResponse response) throws ClassNotFoundException {
        BdEnumFuzzy enumFuzzy = new BdEnumFuzzy();
        enumFuzzy.setEdEdId(1).setEdId(0).setEdOrder(0).setEdParentCode("RD_DeptUFIDARelation").setSysId("UFIDA");
        List<DeptUFIDARelationVO> list = new GetVos<DeptUFIDARelationVO>().getVos(enumFuzzy, DeptUFIDARelationVO.class);
        excelTransfer.exportExcel(response, list, "用友科室", "sheet", DeptUFIDARelationVO.class);
    }

    class GetVos<T> {
        private List<T> getVos(BdEnumFuzzy enumFuzzy, Class<T> data) {
            List<BdEnumdetail> enumRelationInfos = baseMapper.listEnumDetailIsLink(enumFuzzy);
            List<T> list = new ArrayList<>();
            enumRelationInfos.forEach(e -> {
                try {
                    T o = data.newInstance();
                    e.setRowStatus(
                            "0".equals(e.getRowStatus()) ? EnumIsUse.USE.toString() : EnumIsUse.NO_USE.toString());
                    BeanUtils.copyProperties(e, o);
                    list.add(o);
                } catch (InstantiationException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            });
            return list;
        }
    }

    /**
     * 查询HIS的对应关系
     * @param entity
     * @return
     */
//    @Override
//    public ResultObject listEnumDetailIsLinkByHIS(BdEnumdetail entity) {
//        List<EnumRelationInfo> enumRelationInfoList = baseMapper.listEnumDetailIsLinkByHIS(entity);
//        // 存放已关联
//        List<EnumRelationInfo> linked = new ArrayList<>();
//        // 存放未关联
//        List<EnumRelationInfo> unlinked = new ArrayList<>();
//        return null;
//    }

    /**
     * 更新工资对应关系的启用状态
     * @param entity
     * @return
     */

    /**
     * 根据edId查询 科室-工资对应详情
     * @param edId
     * @return 返回两列name集合
     */
//    @Override
//    public ResultObject getEnumDetailWithSalary(String edId) {
//        LambdaQueryWrapper<BdEnumdetail> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(BdEnumdetail::getEdId, edId);
//        BdEnumdetail bdEnumdetail = baseMapper.selectOne(queryWrapper);
//        if (bdEnumdetail == null){
//            ResultObject.errorReturn("条目不存在");
//        }
//        NameCodeVO nameCodeVO = new NameCodeVO();
//        nameCodeVO.setEdExtraFirstCode(bdEnumdetail.getEdExtraFirstCode());
//        nameCodeVO.setEdExtraSecondCode(bdEnumdetail.getEdExtraSecondCode());
//        nameCodeVO.setEdExtraFirstDescription(bdEnumdetail.getEdExtraFirstDescription());
//        nameCodeVO.setEdExtraSecondDescription(bdEnumdetail.getEdExtraSecondDescription());
//        return ResultObject.successReturn(nameCodeVO);
//    }

    /**
     * 更新 科室-工资对应的一些基本信息
     * @return
     */
//    @Override
//    public Response updateEnumDetailWithSalaryInfo(BdEnumBaseInfo baseInfo) {
//        BdEnumdetail entity = new BdEnumdetail();
//        // 设定的最后的更新时间
//        Date currDate = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
//        entity.setUpdatedOn(sdf.format(currDate));
//        // 设定最后更新人  默认为System
//        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
//        userName = userName == null || userName.isEmpty() ? "System" : userName;
//        LambdaUpdateWrapper<BdEnumdetail> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(BdEnumdetail::getEdId, baseInfo.getEdId());
//        entity.setEdExtraFirstCode(baseInfo.getEdExtraFirstCode());
//        entity.setEdExtraSecondCode(baseInfo.getEdExtraSecondCode());
//        entity.setEdExtraFirstDescription(baseInfo.getEdExtraFirstDescription());
//        entity.setEdExtraSecondDescription(baseInfo.getEdExtraSecondDescription());
//        int update = baseMapper.update(entity, updateWrapper);
//        if (update != 0){
//            return Response.success("保存成功");
//        }else {
//            return Response.error("保存失败");
//        }
//    }

    /**
     * 根据edId更新his对应的status
     *
     * @param entity
     * @return
     */
//    @Override
//    public Response updateHisStatusByEdId(BdEnumdetail entity) {
//        int i = baseMapper.updateById(entity);
//        if (i != 0){
//            return Response.success("修改成功");
//        }else {
//            return Response.error("修改失败");
//        }
//    }
    private void setEntityValue(BdEnumdetail entity) {
        Date currDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        entity.setCreatedOn(sdf.format(currDate));
        entity.setUpdatedOn(sdf.format(currDate));
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        userName = userName == null || userName.isEmpty() ? "System" : userName;
        entity.setCreatedBy(userName);
        entity.setUpdatedBy(userName);
//        return entity;
    }
}
